package com.kkb.shopcenter.controller;

import com.csvreader.CsvWriter;
import com.github.pagehelper.PageInfo;
import com.kkb.shopcenter.api.CategoryInfoService;
import com.kkb.shopcenter.common.common.HttpResult;
import com.kkb.shopcenter.common.pojo.CategoryInfo;
import com.kkb.shopcenter.common.utils.FileUtil;
import io.netty.handler.codec.http.multipart.FileUpload;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;


@RestController
@RequestMapping("api")
public class CategoryInfoController {

    private  static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Reference
    private CategoryInfoService categoryInfoService;


    @GetMapping("/queryCategory")
    public HttpResult queryAllCategory(@RequestParam(value = "page",defaultValue = "1") int pageNum,
                                       @RequestParam(value = "pageSize",defaultValue = "10") int pageSize){
        PageInfo pageInfo = categoryInfoService.selectAllCategory();

        return HttpResult.success(pageInfo);

    }

    @GetMapping("/queryCategoryLevel2")
    public HttpResult queryCategoryLevel2(){
        List<CategoryInfo> categoryInfo2 = categoryInfoService.selectCategoryLevel2();
        return HttpResult.success(categoryInfo2);

    }

    @GetMapping("/createCategoryCsv")
    public HttpResult createCsv(){
        String filepath = "/Users/hadoop/Desktop/categroy.csv";
        int result = 0;
        CsvWriter csvWriter = null;
        try {
            csvWriter = new CsvWriter(filepath,',', Charset.forName("utf-8"));
            String[] headers = {"ID","分类名称","父ID","层级","顺序","状态","创建时间","更新时间"};
            csvWriter.writeRecord(headers);
            List<CategoryInfo> categoryInfos = categoryInfoService.selectCategoryList();

            for(CategoryInfo categoryInfo:categoryInfos){
                List<String> contentlist = new ArrayList<>();
                contentlist.add(String.valueOf(categoryInfo.getId()));
                contentlist.add(categoryInfo.getCategoryName());
                contentlist.add(String.valueOf(categoryInfo.getParentId()));
                contentlist.add(String.valueOf(categoryInfo.getLevel()));
                contentlist.add(String.valueOf(categoryInfo.getSort()));
                contentlist.add(String.valueOf(categoryInfo.getStatus()));
                contentlist.add(sdf.format(categoryInfo.getCreateTime()));
                contentlist.add(sdf.format(categoryInfo.getUpdateTime()));

                String[] array = contentlist.toArray(new String[contentlist.size()]);
                csvWriter.writeRecord(array);
                result++;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(csvWriter!=null){
                csvWriter.close();
            }
        }

        return HttpResult.success(result);
    }

    @GetMapping("/downloadAllCategory")
    public void downloadAllCategory(HttpServletRequest request, HttpServletResponse response) throws IOException {

        String fileName = "categroy.csv";
        String realPath = "/Users/hadoop/Desktop";
        File file = new File(realPath,fileName);

        FileInputStream fis =null;
        BufferedInputStream  bis = null;
        if(file.exists()){
         try {
            // 配置文件下载
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            // 下载文件能正常显示中文

            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

            byte[] buffer = new byte[1024];
                 fis = new FileInputStream(file);
                  bis = new BufferedInputStream(fis);

                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while(i!=-1){
                    os.write(buffer,0,i);
                    i  = bis.read(buffer);
                }

                System.out.println("Download the file successfully");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }finally{
             if(bis!=null){
                 bis.close();
             }

             if(fis!=null){
                 fis.close();
             }
         }
        }
    }

    @PostMapping("/uploadAllCategory")
    public HttpResult updateLoadFile(@RequestParam("file") MultipartFile mfile){
        boolean b = false;
        String direct = "/Users/hadoop/Desktop";
        File file = FileUtil.toFile(mfile,direct);
        try {
             b = file.createNewFile();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return  HttpResult.success(b);
    }
}
